package com.qmx.smedicinebox.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmx.smedicinebox.config.Ocr;
import com.qmx.smedicinebox.constant.Constant;
import com.qmx.smedicinebox.sys.dao.MedicationPictureDao;
import com.qmx.smedicinebox.sys.entity.MedicationPictureEntity;
import com.qmx.smedicinebox.sys.entity.MedicineEntity;
import com.qmx.smedicinebox.sys.service.MedicationPictureService;
import com.qmx.smedicinebox.sys.service.MedicationSituationService;
import com.qmx.smedicinebox.sys.service.MedicineService;
import com.qmx.smedicinebox.utils.*;
import com.qmx.smedicinebox.vo.MedicationPictureVo;
import jakarta.xml.bind.DatatypeConverter;
import org.apache.tomcat.util.bcel.Const;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Objects;


@Service("medicationPictureService")
public class MedicationPictureServiceImpl extends ServiceImpl<MedicationPictureDao, MedicationPictureEntity> implements MedicationPictureService {
    @Autowired
    private MedicationSituationService medicationSituationService;

    @Autowired
    private MedicineService medicineService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MedicationPictureEntity> page = this.page(
                new Query<MedicationPictureEntity>().getPage(params),
                new QueryWrapper<MedicationPictureEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R getImgBin(String ans) {
        System.out.println("ans: " + ans);
        JSONObject jsonObject = new JSONObject(ans);

        String deciveId = jsonObject.getString("id");
        String hexString = jsonObject.getString("hexString");
        Date date = new Date();


        System.out.println("id:"+ deciveId);
        System.out.println("hexString: " + hexString);

        // 标识前置信息
        MedicationPictureEntity medicationPictureEntity = new MedicationPictureEntity();
        medicationPictureEntity.setPDate(date);
        medicationPictureEntity.setPDevice(Integer.parseInt(deciveId));

//        ImageIO.setCacheDirectory(new File("src/main/resources/static"));
        ImageIO.setCacheDirectory(new File("/www/wwwroot/tmp"));

        // 将十六进制的字符串转换为字节数组
        byte[] imageBytes = DatatypeConverter.parseHexBinary(hexString);
        // 将字节数组转换为输入流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes);
        // 读取输入流中的数据，生成图片并保存到指定路径
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(byteArrayInputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 默认选择在项目根路径下
        File folder = new File("/www/wwwroot/tmp");  // 将图片打开
        if(!folder.exists()){
            folder.mkdir();
        }
        System.out.println("找到相应文件夹");

        // 获取当前时间，转成字符串
        String format = DateTimeUtil.TransformDateTimeToString(date, Constant.EMPTY,Constant.UNDERSCORE,Constant.EMPTY);
//        String path = img.getUserId() + "_" + id + "_" + "temImg.png";
        String path = deciveId + "_" + format + ".png";
//        String path = "26_2023-5-25.png";
//        File file = new File(folder, path);
        String filePath = "/www/wwwroot/tmp" + "/" + path;
        System.out.println("路径：" + filePath);
        File file = new File(filePath);

        String s = Ocr.generalBasic(filePath);

        MedicineEntity medicine = medicineService.equalMedicineName(s);

        if(Objects.isNull(medicine)){
            return R.error("图片识别不了");
        }

        boolean flag = medicationSituationService.determineSave(medicine.getMId());
        if(flag == false) return R.error("这个药品近五分钟已经吃过一遍了");


//        file.createNewFile();
//        ImageIO.setUseCache();  //设置内存缓存
        try {
            ImageIO.write(bufferedImage, "png", file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 调用工具类将图片上传
        String link = OssUtil.upload(file,path);
        System.out.println(link);

        // 将链接保存到数据库
        medicationPictureEntity.setPFilepath(link);
        System.out.println("需要保存的IMG数据： " + link);


        //新增一条新的用药情况记录
        System.out.println("新增一条新的用药情况记录");
        medicationSituationService.insertNewRecord(Integer.valueOf(deciveId),link,medicine);

        int insert = this.baseMapper.baseInsert(medicationPictureEntity);
        if(insert == 0){
            return R.error("插入数据失败");
        }

        // 将临时文件删除
        if (!file.delete()) {
            System.out.println("Failed to delete file: " + file.getAbsolutePath());
        }
        return R.ok("文件上传成功");
    }

}